<template>
    <div style="height: 100%;" ref="contentRef">
        <navbar :title="$t('mod_exit_save')" :backCallback="back">
            <template #right>
                <a class="add-btn" style="color: #000" v-if="isDown" :href="src" download>
                    {{ $t('lab_download') }}
                </a>
            </template>
        </navbar>
        <div class="header-title-01 header-title-05 horizontal-screen" :style="{'height': horizontalDivHeight}" v-show="isHorizontalScreen" @click.once="back()">
            <span class="icon-back"  @click.once="back()"></span>
            <h1 class="title">
                <div>
                    <span v-html="$t('mod_exit_save_2')"></span>
                </div>
            </h1>
        </div>
        <div :class="{'content-noBottom': !isHorizontalScreen, 'is-head': !isShowHead}" :style="{'height': isHorizontalScreen ? horizontalDivHeight: 'auto'}">
            <div class="detail-video" :style="{'width': isHorizontalScreen ? 'calc(100% - 48px)' : '100%'}" :class="{'HorizontalScreen': isHorizontalScreen}">
                <noticeBar class="notice" v-if="detailData.watermarkInd" :text="detailData.acpWatermark"></noticeBar>
                <xg-player v-if="isShow" :data-idkey="modId" :style="{'width': isHorizontalScreen ? 'calc(100% - 46px)' : '100%', 'padding-top': '0'}"
                    :class="{'hideVideo': isHide}"
                    ref="video" :videoConfig="videoConfig" :modOpenTrial="modOpenTrial"
                    :modDrag="modDrag" :iosTimes="iosTimes" @playerVideo='playerVideo'
                    :fastForward="fastForward" @on-goLandscape="goLandscape"></xg-player>
            </div>
        </div>
        <verification-code v-if="isHandUp" @overtime-code="handleOverTime" @pass-code="passCode"></verification-code>
        <face-modal ref="faceVod" :visibleModal="visibleModal" @takePictures='takePictures'  @takingError='takingError' :busId='modId'
            :distinguishType="'TRAIN_COURSE_VOD'" :ufrId="ufrId" @closeFace='closeFace'>
            <div slot="down" style="text-align:center;padding:10px 0 0;color:#F56C6C;font-size:16px">{{second}} {{$t('automatically_exit')}}</div>
        </face-modal>
    </div>
</template>

<script>
import verificationCode from '@/repeatComponents/verification-code/verification-code';
import xgPlayer from '../player/xgplayer';
import faceModal from '@/components/faceModal/faceModal';
import noticeBar from './notice-bar';
export default {
    name: 'VodContent',
    components: {xgPlayer,
                 faceModal,
                 noticeBar,
                 verificationCode},
    data() {
        return {
            second: 30, //人脸倒计时
            intervalNull: null,
            visibleModal: false,
            faceTime: 0,
            faceIndex: 0,
            faceList: [],
            ufrId: 0,
            isHide: false,
            videoKey: 1,
            curTime: 0, // 最后一次播放时间点
            player: {},
            overTime: false, // 是否超时
            isHandUp: false,
            modHangUpTime: 0, // 防挂机间隔时间
            handTimer: {}, // 定时器
            handTimes: 0, // 定时器初始时间（s）
            handCurTime: 0, // 视频断点上一次续播时间（用于防挂机）
            isDown: false,
            src: '',
            data: {},
            isPlayVideo: false,
            isFromMobile: false,
            isHorizontalScreen: false,
            screenWidth: document.body.clientWidth,
            screenHeight: document.body.clientHeight,
            curLan: window.localStorage.getItem('globalLang'),
            modId: this.$route.params.modId,
            horizontalDivHeight: '100%',
            /*--------------新的参数*/
            detailData: {},
            startTime: new Date().getTime(), //开始时间
            videoFlag: '', //标志
            type: '', //类型 VOD AUD
            currentTime: 0, // 最后一次播放时间点
            videoConfig: {
                videoUrl: '', // 播放地址
                lastPlayTime: '' // 上次播放时间
            },
            modOpenTrial: true, // 权限控制
            modDrag: true,
            iosTimes: false,
            videoPlayer: '',
            currCourse: '',
            isShow: false,
            palpitate: {
                isPause: false, // 是否暂停
                itmId: '', // 课程itmId
                modId: '', // 模块resId
                tkhId: '' // 学习跟踪id
            },
            times: null,
            faceVodBack: false,
            sum: '',
            isShowHead: true,
            resVodDuration: '',
            fastForward: null
        };
    },
    methods: {
        goLandscape(val) {
            console.log(val);
            this.isShowHead = val === 'OFF';
        },
        playerVideo(val) {
            this.playHandle(val.currentTime);
            this.videoPlayer = val;
            const viewTime = val.currentTime;
            this.currCourse = 'openPlayer' + this.$route.params.itmId + this.modId;
            localStorage.setItem(this.currCourse, viewTime);
            // this.isFacePhoto(this.videoPlayer);
        },
        // 学习中人脸倒计时
        countDown() {
            // 设置倒计时前先清楚一次定时器,防止存在两个
            clearInterval(this.intervalNull);
            this.intervalNull = setInterval(() => {
                this.second--;
                if (this.second <= 0) { //时间到了自动关闭学习
                    clearInterval(this.intervalNull);
                    this.visibleModal = false;
                    this.$refs.faceVod.closeCamera();
                    this.faceVodBack = true;
                    this.$refs.faceVod.recognitionSuc = false;
                    localStorage.removeItem(this.modId + '-' + this.src.substring(this.src.lastIndexOf('/') + 1), JSON.stringify(this.faceTime));
                    this.back();
                }
            }, 1000);
        },
        closeFace() {
            this.faceVodBack = true;
            localStorage.removeItem(this.modId + '-' + this.src.substring(this.src.lastIndexOf('/') + 1), JSON.stringify(this.faceTime));
            clearInterval(this.intervalNull);
            this.back();
        },
        takePictures() {
            this.second = 30;
            clearInterval(this.intervalNull);
            this.visibleModal = false;
            this.player.play();
            // 人脸识别成功后，改变列表的OFF为ON
            const indexNode = this.faceList.findIndex(node => node.ufrId === this.ufrId);
            this.$set(this.faceList[indexNode], 'ufrStatus', 'ON');
            this.faceIndex++;
        },
        takingError() {
            this.visibleModal = false;
        },
        back() {
            this.$router.go(-1);
            this.setVideoCurrentTime();
            this.faceVodBack = true;
            /*返回保存记录*/
            this.saveRecord();
        },
        setVideoCurrentTime() {
            // 当人脸识别过的视频，再次进入时，从上次播放的时间点开始播放，否则从头开始播放
            // 当没有人脸识别的视频，从上次播放的时间点开始播放
            let time = !(this.faceList[0] && this.faceList[0].ufrStatus === 'OFF') ? this.$refs.video.player.currentTime : 0;
            localStorage.setItem(this.videoFlag, time);
        },
        /*视频播放*/
        playVideo() {
            this.isPlayVideo = true;
            this.$refs.videoPlayer.play();
        },
        /*保存学习记录*/
        saveRecord(id, leave = false, newId, times) {
            this.$toast(this.$t('mod_save_record'));
            const req = {
                entId: this.$route.params.userEntId,
                itmId: this.$route.params.itmId,
                modId: this.modId,
                startTime: this.startTime,
                tkhId: this.$route.params.tkhId
            };
            if (times) {
                req.codeInputTime = times;
            }
            if (times) {
                this.$axios({
                    method: 'GET',
                    url: `/app/api/trainee/course/start_lear_time/${req.modId}`
                }).then(res => {
                    console.log(res);
                    this.startTime = res.data;
                });
            }

            this.$axios({
                method: 'POST',
                url: `/app/api/trainee/course/module/evaluation`,
                data: req
            }).then(res => {
                if (res && times) {
                    // this.startTime = res.data;
                    this.overTime = false;
                    if (this.detailData.modType === 'VOD' || this.detailData.modType === 'AUD') {
                        this.handCurTime = this.player.currentTime;
                        this.player.play();
                    } else {
                        this.player = document.querySelector('video');
                        const viewTime = this.player.currentTime;
                        localStorage.setItem(this.modId + '-' + this.src.substring(this.src.lastIndexOf('/') + 1), JSON.stringify(viewTime)); //缓存时间
                    }
                }
                if (leave) {
                    return true;
                }
            });
        },
        changeHorizontalScreen() {
            // if (this.screenWidth > this.screenHeight) {
            //     this.isHorizontalScreen = true;
            //     if (this.$refs.contentRef.offsetHeight < this.$refs.videoPlayer.offsetHeight) {
            //         this.horizontalDivHeight = (this.$refs.videoPlayer.offsetHeight + 56) + 'px';
            //     } else {
            //         this.horizontalDivHeight = this.$refs.contentRef.offsetHeight + 'px';
            //     }
            // } else {
            //     this.isHorizontalScreen = false;
            // }
            // Watermark.out();
        },
        /**
         * @description: 防挂机间隔定时器
         * @param {*}
         * @return {*}
         */
        handTime() {
            this.handTimes = this.modHangUpTime * 60;
            this.handTimer = setInterval(() => {
                this.handTimes--;
                if (this.handTimes === 0) {
                    clearInterval(this.handTimer);
                    if (this.detailData.modType === 'VOD' || this.detailData.modType === 'AUD') {
                        this.player = document.querySelector('video');
                        this.player.pause();
                        this.isHide = true;
                    }
                    // 当弹出防挂机弹窗时，人脸倒计时暂停
                    if (this.visibleModal === true) {
                        clearInterval(this.intervalNull);
                        this.$refs.faceVod.closeCamera();
                    }
                    this.isHandUp = true;
                    this.overTime = true;
                }
            }, 1000);
            this.$once('hook:beforeDestroy', () => {
                clearInterval(this.handTimer);
            });
        },
        /**
         * @description: 防挂机超时处理
         * @param {*}
         * @return {*}
         */
        handleOverTime() {
            this.overTime = true;
            const viewTime = this.handCurTime;
            localStorage.setItem(this.modId + '-' + this.src.substring(this.src.lastIndexOf('/') + 1), JSON.stringify(viewTime)); //缓存时间
            this.isHandUp = false;
            this.back();
        },
        /**
         * @description: 通过防挂机验证，继续学习
         * @param {*}
         * @return {*}
         */
        passCode(times) {
            this.isHandUp = false;
            // 当防挂机关闭后，人脸倒计时继续
            if (this.visibleModal === true) {
                this.$refs.faceVod.openModal();
                this.countDown();
            }
            this.isHide = false;
            this.saveRecord(this.oldTarget, true, null, times);
            this.handTime();
        },
        /**
         * 处理视频播放时长
         */
        playHandle(times) {
            this.player = document.querySelector('video');
            if (this.player) {
                const viewTime = times || this.player.currentTime;
                this.faceTime = viewTime;
                localStorage.setItem(this.modId + '-' + this.src.substring(this.src.lastIndexOf('/') + 1), JSON.stringify(viewTime)); //缓存时间
                this.faceRecognition(this.player);
            }
        },
        onlineCalculation(type) {
            this.$axios({
                method: 'GET',
                url: `/app/api/data/kanban/online/${type}/calculate`
            }).then(res => {
                console.log(res);
            });
        },
        /**
         * 设置视频播放开始时间
         */
        setTime() {
            // this.startTime = _.now()
            if (this.curTime) {
                this.player = document.querySelector('video');
                this.player.currentTime = this.curTime;
                this.curTime = null;
            }
        },
        setCurrentTime() {
            let time = Number(localStorage.getItem(this.modId + '-' + this.src.substring(this.src.lastIndexOf('/') + 1)));
            if (time && time !== 0) {
                this.currentTime = time;
            }
        },
        //  学习心跳
        palpitateTime() {
            this.$axios({
                method: 'POST',
                url: '/app/api/trainee/course/learn/heartbeat',
                data: this.palpitate
            });
        },
        startTimes() {
            this.palpitate.isPause = false;
        },
        stopTimes() {
            this.palpitate.isPause = false;
        },
        getFaceTime() { // 培训项目-线上课程（视频）- 获取人脸识别随机节点
            this.$axios({
                method: 'POST',
                url: `/app/api/trainee/user-face-gather/getProjectVodNode`,
                data: {
                    itmId: this.$route.params.itmId, // 认证培训课程里面的线上课程的itmId
                    parentItmId: this.$route.query.parentItmId, // 认证培训的itmId
                    ufrBusId: this.modId,
                    // ONLINE_COURSE_VOD:在线课程-视频;ONLINE_COURSE_TEST:在线课程-测验;ONLINE_EXAM_TEST:在线考试-测验;TRAIN_COURSE_VOD:培训项目-线上课程视频;TRAIN_COURSE_TEST:培训项目-线上考试测验
                    ufrBusType: 'TRAIN_COURSE_VOD'
                }
            }).then(res => {
                this.faceList = res.data;
            });
        },
        // 人脸识别
        faceRecognition(player) {
            const time = this.faceTime;
            if (this.faceTime * 1000 > this.detailData.resVodDuration * 1000) {
                return;
            }
            this.player = player;
            if (this.faceList[this.faceIndex] && time * 1000 > this.faceList[this.faceIndex].ufrNode * 1000) {
                if (this.faceList[this.faceIndex].ufrStatus === 'ON') {
                    this.faceIndex++;
                } else if (this.faceList[this.faceIndex].ufrStatus === 'OFF') {
                    player.pause();
                    this.ufrId = this.faceList[this.faceIndex].ufrId;
                    localStorage.setItem('faceIndex', this.faceIndex);
                    this.visibleModal = true;
                    this.countDown();
                }
            }
        }
    },
    destroyed() {
        // this.onlineCalculation('ONLINE_LEARN_DEC');
    },
    beforeMount() {
        if (this.$route.query.type === 'VOD') {
            this.getFaceTime();
        }
    },
    mounted() {
        // 锁定屏幕方向为竖屏
        const plus = window.plus;
        if (window.plus) {
            window.plus.screen.lockOrientation('portrait-primary');
        } else {
            document.addEventListener('plusready', () => {
                plus.screen.lockOrientation('portrait-primary', 'portrait-secondary');
            }, false);
        }
        // this.onlineCalculation('ONLINE_LEARN_INC');
        // this.getFaceInfo();
        this.palpitate.itmId = this.$route.params.itmId;
        this.palpitate.modId = this.$route.params.modId;
        this.palpitate.tkhId = this.$route.params.tkhId;
        /*获取课件详情*/
        this.$axios({
            method: 'GET',
            url: `/app/api/trainee/course/module/detail`,
            params: {
                itmId: this.$route.params.itmId,
                modId: this.modId
            }
        }).then(res => {
            if (res && res.status === 200) {
                // console.log(res.data.modType);
                if (res.data.modType !== 'SCO') {
                    if (res.data.modType === 'VOD' || res.data.modType === 'AUD') {
                        this.palpitate.isPause = false;
                    }
                    // this.times = setInterval(() => {
                    //     this.palpitateTime();
                    // }, 5000);
                }
                this.isDown = res.data.relationVO.modDownloadInd;
                this.type = res.data.modType;
                this.detailData = res.data;
                this.isShow = true;
                this.modHangUpTime = res.data.modHangUpTime;
                this.startTime = res.data.startTime;
                //   this.src = this.appUrl + res.data.sourceUrl;
                this.fastForward = res.data.acpDragInd;
                this.src = this.appUrl + res.data.sourceUrl;
                this.videoFlag = this.modId + '-' + this.src.substring(this.src.lastIndexOf('/') + 1);
                if (this.videoFlag) {
                    this.curTime = JSON.parse(localStorage.getItem(this.videoFlag));
                    this.handCurTime = JSON.parse(localStorage.getItem(this.videoFlag));
                }
                if (this.detailData.modType === 'VOD' || this.detailData.modType === 'AUD') {
                    setTimeout(() => {
                        this.player = document.querySelector('video');
                    }, 0);
                }
                // 若设置了防挂机间隔时间，则初始化定时器。倒计时结束打开弹窗
                if (this.modHangUpTime && this.modHangUpTime !== 0) {
                    this.handTime();
                } else {
                    // 接口报错注释掉
                    //     this.palpitateTime();
                    //     this.times = setInterval(() => {
                    //         this.palpitateTime();
                    //     }, 5000);
                }
                if (!this.iosTimes) {
                    // 当人脸识别过的视频，再次进入时，从上次播放的时间点开始播放，否则从头开始播放
                    // 当没有人脸识别的视频，从上次播放的时间点开始播放
                    let currentTime = !(this.faceList[0] && this.faceList[0].ufrStatus === 'OFF') ? localStorage.getItem(this.videoFlag) : 0;
                    this.videoConfig = {
                        videoUrl: this.appUrl + res.data.sourceUrl,
                        lastPlayTime: currentTime
                    };
                    if (res.data.modType === 'AUD') {
                        this.videoConfig.duration = res.data.audDuration;
                    }
                }
            }
        });
        //监听屏幕宽高的变化
        window.onresize = () => {
            this.screenWidth = document.body.clientWidth;
            this.screenHeight = document.body.clientHeight;
        };
        this.changeHorizontalScreen();
        //视频断点播放
        // this.breakpointplay(this);
        // 设置人脸识别的busId
        window.localStorage.removeItem('face_busId');
        window.localStorage.setItem('face_busId', this.$route.params.modId);
    },
    beforeRouteEnter(to, from, next) {
        next(_this => {
            if (from.path.indexOf('/offline') !== -1) {
                _this.isFromMobile = true;
            }
        });
    },
    beforeDestroy() {
        clearInterval(this.times);
        this.times = null;
    },
    beforeRouteLeave(to, from, next) {
        if (!this.overTime) {
            if (!this.faceVodBack) {
                this.saveRecord();
            }
        } else {
            console.log(this.handCurTime);
        }
        // const viewTime = this.currentTime;
        // console.log(this.modId + '-' + this.src.substring(this.src.lastIndexOf('/') + 1), JSON.stringify(viewTime));
        // localStorage.setItem(this.modId + '-' + this.src.substring(this.src.lastIndexOf('/') + 1), JSON.stringify(viewTime)); //缓存时间
        // console.log(viewTime);
        next();
    },
    watch: {
        screenWidth(val) {
            this.changeHorizontalScreen();
        },
        screenHeight(val) {
            this.changeHorizontalScreen();
        }
    }
};
</script>

<style scoped lang="less">
    .detail-video {
        position: relative;
        width: 100%;
        min-height: 200px;
        max-height: 100%;
        margin: 0 auto;
        &.HorizontalScreen{
            top: 15%;
            // margin-top: -15%;
            max-height: 75% !important;
        }
    }
    .detail-video .video-icon-box {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        z-index: 5;
    }
    .detail-video .video-icon{
        width: 56px;
        height: 56px;
        display: flex;
        border-radius: 100%;
        background: rgba(0,0,0,.5);
        position: absolute;
        justify-content: center;
        align-items: center;
        top: 50%;
        margin-top: calc(-56px / 2);
        left: 50%;
        margin-left: calc(-56px / 2);
        z-index: 6;
    }
    .detail-video .video-icon:after{
        content: '';
        display: block;
        width: 16px;
        height: 20px;
        background: url(../../../static/images/icon-05.png) no-repeat 2px -1px;
        background-size: 15px;
    }
    .detail-video video{
        width: 100%;
        /*height: 100%;*/
        max-height: 300px;
        position: relative;
        z-index: 2;
    }
    .horizontal-screen {
        width: 48px;
        position: absolute;
        top: 0;
        right: 0;
        background: #ffffff;
        padding: 0;
        .title {
            width: 48px;
            margin: 0 auto;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100%;
            font-size: 1.2em;
            color: #1a1a1a;
            font-weight: bold;
            text-align: center;
        }
    }
    .ask-in {
        content: " ";
        display: inline-block;
        width: 24px;
        height: 20px;
        background: url(./images/ts_L01_gray.png) no-repeat 4px 0;
        background-size: 20px;
        margin-bottom: -4px;
    }
    .add-btn {
        height: 55px;
        line-height: 55px;
        padding: 0 15px;
        font-size: 16px;
        color: #000;
    }
    /deep/.code-popup{
      min-width: 80%;
    }
    .hideVideo{
      /deep/video{
        display: none;
      }
    }
    .cancelProgress{
      /deep/.vjs-progress-control {
        display:none;
      }
      /deep/.xgplayer-progress {
        display:none;
      }
    }
    .notice{
      position: absolute;
      top: 10px;
      left: 0;
      z-index: 9999
    }
    /deep/ .xgplayer-skin-default.xgplayer-rotate-fullscreen{
        // width: calc(100vh - 56px) !important;
        // left: 96%;
        // height: 92vw !important;
    }
    .is-head {
        padding: 0px 0 0 !important;
    }
    /deep/.van-nav-bar__title {
        margin: 15px;
    }
</style>
